<template>
  <div class="serverPage">
    <video id="video-player" controls width="600" height="400">
    </video>
  </div>
</template>

<script>
import { loginApi, urlApi, openPlayApi } from '@/api/server'
import FLVPlayer from 'flv.js';
export default {
  data() {
    return {
      token: '',
      url: '',
      flvPlayer: null
    }
  },
  methods: {
    // 获取token
    async handleLogin() {
      if (this.token) return
      let { data } = await loginApi({
        appKey: '7n74idt55380bbpf7755gwonh0oh0usl',
        appSecret: 'yqq9xrp8ev7uitrggz1neawa0weh0e'
      })
      this.token = data.accessToken
      // const expirySeconds = data.expireTime; // 86400000 秒等于 1 天
      // Cookies.set('servertoken', this.token, { expires: expirySeconds / (60 * 60 * 24) }); // `expires` 需要以天为单位
      this.getURL()
    },
    // 获取url
    async getURL() {
      let { data } = await urlApi({
        accessToken: this.token,
        romId: 'ffff2941009c9b85'
      })
      this.url = data.playUrl
      this.open()
    },
    // 开启播放
    async open() {
      await openPlayApi({
        accessToken: this.token,
        romId: 'ffff2941009c9b85',
        playUrl: this.url
      })
      this.flv()
    },
    // flv
    flv() {
      const videoElement = document.getElementById('video-player');

      if (FLVPlayer.isSupported()) {
        const flvPlayer = FLVPlayer.createPlayer({
          type: 'flv',
          url: this.url
        }, { enableStashBuffer: false });

        flvPlayer.attachMediaElement(videoElement);
        flvPlayer.load();
        flvPlayer.play();
      } else {
        console.error('FLV.js is not supported.');
      }
    },
  },
  mounted() {
    this.handleLogin()
  },
  destroyed() {
    if (this.flvPlayer) {
      this.flvPlayer.destroy();
    }
  }
}
</script>

<style lang='scss' scoped>
.serverPage {
  width: 100%;
  height: calc(100vh - 50px);
}

video {
  width: 100%;
  height: 100%;
}
</style>
